package com.feicheng.service.a;

import com.alibaba.fastjson.JSONObject;
import com.feicheng.common.mt.Mtmd;
import com.feicheng.persistence.entity.Amd;
import com.feicheng.persistence.service.IAmdService;
import com.meituan.sdk.MeituanClient;
import com.meituan.sdk.MeituanResponse;
import com.meituan.sdk.auth.MeituanTokenData;
import com.meituan.sdk.auth.MeituanTokenResponse;
import com.meituan.sdk.internal.exceptions.MtSdkException;
import com.meituan.sdk.model.ddzh.tuangou.tuangouDealQueryshopdeal.RshopDeal;
import com.meituan.sdk.model.ddzh.tuangou.tuangouDealQueryshopdeal.TuangouDealQueryshopdealRequest;
import com.meituan.sdk.model.ddzh.tuangou.tuangouDealQueryshopdeal.TuangouDealQueryshopdealResponse;
import com.meituan.sdk.model.ddzh.tuangou.tuangouReceiptQuerybymobile.TuangouReceiptQuerybymobileRequest;
import com.meituan.sdk.model.ddzh.tuangou.tuangouReceiptQuerybymobile.TuangouReceiptQuerybymobileResponse;
import com.meituan.sdk.model.ddzh.tuangou.tuangouReceiptQuerybymobile.UserReceiptDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;

@Slf4j
@Service
public class FMtService {

    @Autowired
    private MeituanClient mtclient;

    @Autowired
    IAmdService iAmdService;

    public Mtmd build(String mdid) {
        Amd amd = iAmdService.getById(mdid);
        JSONObject mtconfigObject = amd.getMtconfig();
        Mtmd mtmd = mtconfigObject.toJavaObject(Mtmd.class);
        return this.checkToken(mtmd);
    }

    private Long toEpochSecond(LocalDateTime lt) {
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zonedDateTime = lt.atZone(zoneId);
        Instant instant = zonedDateTime.toInstant();
        return instant.getEpochSecond();
    }

    public Mtmd checkToken(Mtmd mtmd) {
        if (StringUtils.hasLength(mtmd.getAccessToken())) {
            long scha = this.toEpochSecond(mtmd.getGqsj()) - this.toEpochSecond(LocalDateTime.now());
            if (scha < (3600L * 24)) {
                MeituanTokenData tokenData = this.refreshToken(mtmd);
                mtmd.setAccessTokenData(tokenData);
                return mtmd;
            } else {
                return mtmd;
            }
        } else {
            return mtmd;
        }
    }

    private MeituanTokenData refreshToken(Mtmd mtmd) {
        try {
            MeituanTokenResponse tokenResponse = mtclient.refreshToken(58, mtmd.getRefreshToken());

            if (tokenResponse.isSuccess()) {
                return tokenResponse.getData();
            }
        } catch (MtSdkException e) {
            log.error("刷新美团token出现错误", e);
        }
        return null;
    }

    public Mtmd newMtmd(String code, String mdid) {
        MeituanTokenData tokenData = this.newAccessToken(code);
        if (null != tokenData) {
            Mtmd mtmd = new Mtmd(mdid);
            mtmd.setAccessTokenData(tokenData);
            Amd amd = iAmdService.getById(mdid);
            amd.setMtconfig((JSONObject) JSONObject.toJSON(mtmd));
            iAmdService.updateById(amd);
            return mtmd;
        } else {
            return null;
        }
    }

    private MeituanTokenData newAccessToken(String code) {
        try {
            MeituanTokenResponse tokenResponse = mtclient.getOAuthToken(58, code);
            if (tokenResponse.isSuccess()) {
                return tokenResponse.getData();
            }
        } catch (MtSdkException e) {
            log.error("刷新美团token出现错误", e);
        }
        return null;
    }

    public List<RshopDeal> tuangouDealQuery(JSONObject param) {

        String mdid = param.getString("mdid");
        Amd amd = iAmdService.getById(mdid);
        JSONObject mtconfigObject = amd.getMtconfig();
        Mtmd mtmd = mtconfigObject.toJavaObject(Mtmd.class);

        TuangouDealQueryshopdealRequest request = new TuangouDealQueryshopdealRequest();
        request.setSource(2);
        request.setOffset(1);
        List<RshopDeal> shopDeals = null;

        try {
            //发起接口调用
            MeituanResponse<TuangouDealQueryshopdealResponse> response = mtclient.invokeApi(request, mtmd.getAccessToken());
            //判断是调用是否成功
            if (response.isSuccess()) {
                //调用成功，通过getData获取接口响应数据
                TuangouDealQueryshopdealResponse tuangouDealQueryshopdealResponse = response.getData();
                shopDeals = tuangouDealQueryshopdealResponse.getResult();
            }
        } catch (MtSdkException e) {
            log.error("取得团购信息出错", e);
        }

        return shopDeals;
    }

    public List<UserReceiptDTO> tuangouReceiptQuerybymobile(JSONObject param) {
        String mdid = param.getString("mdid");
        Amd amd = iAmdService.getById(mdid);
        JSONObject mtconfigObject = amd.getMtconfig();
        Mtmd mtmd = mtconfigObject.toJavaObject(Mtmd.class);

        String mobile = param.getString("mobile");
        Long dealGroupId = param.getLong("dealGroupId");
        Long dealId = param.getLong("dealId");

        TuangouReceiptQuerybymobileRequest request = new TuangouReceiptQuerybymobileRequest();
        request.setMobile(mobile);
        request.setDealGroupId(dealGroupId);
        request.setDealId(dealId);
        request.setOffset(1);
        List<UserReceiptDTO> userReceiptDTOs = null;

        try {
            //发起接口调用
            MeituanResponse<TuangouReceiptQuerybymobileResponse> response = mtclient.invokeApi(request, mtmd.getAccessToken());
            //判断是调用是否成功
            if (response.isSuccess()) {
                //调用成功，通过getData获取接口响应数据
                TuangouReceiptQuerybymobileResponse tuangouReceiptQuerybymobileResponse = response.getData();
                userReceiptDTOs = tuangouReceiptQuerybymobileResponse.getResult();
            }
        } catch (MtSdkException e) {
            log.error("取得可用的核销券信息出错", e);
        }
        return userReceiptDTOs;
    }


}
